<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>数据分析 - 智能设备控制中心</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css">
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <style>
        body {
            background-color: #f8f9fa;
        }
        .chart-container {
            position: relative;
            margin: auto;
            height: 400px;
            width: 100%;
        }
        .small-chart {
            height: 300px;
        }
        .stat-card {
            transition: transform 0.3s, box-shadow 0.3s;
        }
        .stat-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 10px 20px rgba(0,0,0,0.1);
        }
        .nav-link {
            color: #495057;
        }
        .nav-link.active {
            color: #0d6efd;
            font-weight: bold;
        }
        .date-range-picker {
            display: flex;
            align-items: center;
            gap: 10px;
        }
        .custom-tabs .nav-link {
            border-top-left-radius: 0.375rem;
            border-top-right-radius: 0.375rem;
        }
        .custom-tabs .nav-link.active {
            background-color: #fff;
            border-color: #dee2e6 #dee2e6 #fff;
        }
    </style>
</head>
<body>
    <nav class="navbar navbar-expand-lg navbar-light bg-white shadow-sm mb-4">
        <div class="container">
            <a class="navbar-brand" href="/">
                <i class="fa fa-home mr-2"></i>智能设备控制中心
            </a>
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse" id="navbarNav">
                <ul class="navbar-nav ml-auto">
                    <li class="nav-item">
                        <a class="nav-link" href="/">首页</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="/devices">设备</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="/scenes">场景</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="/schedules">定时任务</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link active" href="/analytics">数据分析</a>
                    </li>
                </ul>
            </div>
        </div>
    </nav>

    <div class="container">
        <div class="row">
            <div class="col">
                <h2 class="mb-4"><i class="fa fa-bar-chart text-primary"></i> 数据分析</h2>
                <p class="mb-4">查看您的智能设备使用数据和能耗分析，帮助您优化能源消耗和设备使用习惯。</p>
            </div>
        </div>

        <!-- 时间范围选择 -->
        <div class="row mb-4">
            <div class="col-md-6">
                <div class="date-range-picker">
                    <label for="startDate" class="form-label mb-0">开始日期:</label>
                    <input type="date" id="startDate" class="form-control" value="{{ start_date }}">
                    <label for="endDate" class="form-label mb-0">结束日期:</label>
                    <input type="date" id="endDate" class="form-control" value="{{ end_date }}">
                    <button class="btn btn-primary" onclick="updateAnalytics()">更新</button>
                </div>
            </div>
            <div class="col-md-6 text-right">
                <div class="btn-group" role="group">
                    <button class="btn btn-outline-primary" onclick="setTimeRange('today')">今天</button>
                    <button class="btn btn-outline-primary" onclick="setTimeRange('week')">本周</button>
                    <button class="btn btn-outline-primary" onclick="setTimeRange('month')">本月</button>
                    <button class="btn btn-outline-primary" onclick="setTimeRange('year')">今年</button>
                </div>
            </div>
        </div>

        <!-- 统计卡片 -->
        <div class="row mb-6">
            <div class="col-md-3 mb-4">
                <div class="card stat-card bg-primary text-white">
                    <div class="card-body">
                        <h5 class="card-title"><i class="fa fa-bolt mr-2"></i> 总用电量</h5>
                        <p class="card-text h3">{{ total_energy }} kWh</p>
                        <p class="card-text">{{ energy_change }}% 与上期相比</p>
                    </div>
                </div>
            </div>
            <div class="col-md-3 mb-4">
                <div class="card stat-card bg-success text-white">
                    <div class="card-body">
                        <h5 class="card-title"><i class="fa fa-clock-o mr-2"></i> 运行时长</h5>
                        <p class="card-text h3">{{ total_runtime }} h</p>
                        <p class="card-text">{{ runtime_change }}% 与上期相比</p>
                    </div>
                </div>
            </div>
            <div class="col-md-3 mb-4">
                <div class="card stat-card bg-info text-white">
                    <div class="card-body">
                        <h5 class="card-title"><i class="fa fa-plug mr-2"></i> 活跃设备</h5>
                        <p class="card-text h3">{{ active_devices }} 台</p>
                        <p class="card-text">{{ active_ratio }}% 的设备处于活跃状态</p>
                    </div>
                </div>
            </div>
            <div class="col-md-3 mb-4">
                <div class="card stat-card bg-warning text-white">
                    <div class="card-body">
                        <h5 class="card-title"><i class="fa fa-tint mr-2"></i> 平均湿度</h5>
                        <p class="card-text h3">{{ avg_humidity }}%</p>
                        <p class="card-text">{{ humidity_status }}</p>
                    </div>
                </div>
            </div>
        </div>

        <!-- 标签页 -->
        <div class="row mb-4">
            <div class="col">
                <ul class="nav nav-tabs custom-tabs" id="analyticsTabs" role="tablist">
                    <li class="nav-item" role="presentation">
                        <button class="nav-link active" id="energy-tab" data-bs-toggle="tab" data-bs-target="#energy-tab-pane" type="button" role="tab">
                            <i class="fa fa-bolt mr-2"></i>能耗分析
                        </button>
                    </li>
                    <li class="nav-item" role="presentation">
                        <button class="nav-link" id="usage-tab" data-bs-toggle="tab" data-bs-target="#usage-tab-pane" type="button" role="tab">
                            <i class="fa fa-line-chart mr-2"></i>使用模式
                        </button>
                    </li>
                    <li class="nav-item" role="presentation">
                        <button class="nav-link" id="environment-tab" data-bs-toggle="tab" data-bs-target="#environment-tab-pane" type="button" role="tab">
                            <i class="fa fa-leaf mr-2"></i>环境监测
                        </button>
                    </li>
                    <li class="nav-item" role="presentation">
                        <button class="nav-link" id="recommendations-tab" data-bs-toggle="tab" data-bs-target="#recommendations-tab-pane" type="button" role="tab">
                            <i class="fa fa-lightbulb-o mr-2"></i>节能建议
                        </button>
                    </li>
                </ul>
            </div>
        </div>

        <!-- 标签页内容 -->
        <div class="tab-content" id="analyticsTabsContent">
            <!-- 能耗分析 -->
            <div class="tab-pane fade show active" id="energy-tab-pane" role="tabpanel">
                <div class="row">
                    <div class="col-md-8 mb-4">
                        <div class="card">
                            <div class="card-header">
                                <h5 class="card-title">能耗趋势</h5>
                            </div>
                            <div class="card-body">
                                <div class="chart-container">
                                    <canvas id="energyTrendChart"></canvas>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-4 mb-4">
                        <div class="card">
                            <div class="card-header">
                                <h5 class="card-title">设备能耗分布</h5>
                            </div>
                            <div class="card-body">
                                <div class="chart-container small-chart">
                                    <canvas id="energyDistributionChart"></canvas>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="row">
                    <div class="col-md-6 mb-4">
                        <div class="card">
                            <div class="card-header">
                                <h5 class="card-title">房间能耗对比</h5>
                            </div>
                            <div class="card-body">
                                <div class="chart-container small-chart">
                                    <canvas id="roomEnergyChart"></canvas>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-6 mb-4">
                        <div class="card">
                            <div class="card-header">
                                <h5 class="card-title">用电高峰时段</h5>
                            </div>
                            <div class="card-body">
                                <div class="chart-container small-chart">
                                    <canvas id="peakHoursChart"></canvas>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 使用模式 -->
            <div class="tab-pane fade" id="usage-tab-pane" role="tabpanel">
                <div class="row">
                    <div class="col-md-8 mb-4">
                        <div class="card">
                            <div class="card-header">
                                <h5 class="card-title">设备使用时长趋势</h5>
                            </div>
                            <div class="card-body">
                                <div class="chart-container">
                                    <canvas id="usageTrendChart"></canvas>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-4 mb-4">
                        <div class="card">
                            <div class="card-header">
                                <h5 class="card-title">设备使用率</h5>
                            </div>
                            <div class="card-body">
                                <div class="chart-container small-chart">
                                    <canvas id="usageRateChart"></canvas>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="row">
                    <div class="col">
                        <div class="card">
                            <div class="card-header">
                                <h5 class="card-title">使用习惯分析</h5>
                            </div>
                            <div class="card-body">
                                <div class="table-responsive">
                                    <table class="table table-hover">
                                        <thead>
                                            <tr>
                                                <th>设备名称</th>
                                                <th>平均开启时间</th>
                                                <th>平均关闭时间</th>
                                                <th>使用频率</th>
                                                <th>建议调整</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            {% for device in usage_patterns %}
                                            <tr>
                                                <td>{{ device.name }}</td>
                                                <td>{{ device.avg_on_time }}</td>
                                                <td>{{ device.avg_off_time }}</td>
                                                <td>{{ device.frequency }}</td>
                                                <td>{{ device.suggestion }}</td>
                                            </tr>
                                            {% endfor %}
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 环境监测 -->
            <div class="tab-pane fade" id="environment-tab-pane" role="tabpanel">
                <div class="row">
                    <div class="col-md-6 mb-4">
                        <div class="card">
                            <div class="card-header">
                                <h5 class="card-title">温度变化趋势</h5>
                            </div>
                            <div class="card-body">
                                <div class="chart-container">
                                    <canvas id="temperatureChart"></canvas>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-6 mb-4">
                        <div class="card">
                            <div class="card-header">
                                <h5 class="card-title">湿度变化趋势</h5>
                            </div>
                            <div class="card-body">
                                <div class="chart-container">
                                    <canvas id="humidityChart"></canvas>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="row">
                    <div class="col">
                        <div class="card">
                            <div class="card-header">
                                <h5 class="card-title">环境数据分析</h5>
                            </div>
                            <div class="card-body">
                                <p class="mb-4">基于您的环境数据，以下是一些关键发现：</p>
                                <div class="list-group">
                                    {% for insight in environment_insights %}
                                    <div class="list-group-item">
                                        <i class="fa fa-{{ insight.icon }} mr-2 text-{{ insight.color }}"></i>
                                        <strong>{{ insight.title }}:</strong> {{ insight.description }}
                                    </div>
                                    {% endfor %}
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 节能建议 -->
            <div class="tab-pane fade" id="recommendations-tab-pane" role="tabpanel">
                <div class="row">
                    <div class="col">
                        <div class="card">
                            <div class="card-header">
                                <h5 class="card-title"><i class="fa fa-lightbulb-o text-warning mr-2"></i> AI智能节能建议</h5>
                            </div>
                            <div class="card-body">
                                <p class="mb-4">基于您的使用数据，我们为您提供以下节能和优化建议：</p>
                                <div class="space-y-4">
                                    {% for recommendation in recommendations %}
                                    <div class="bg-{{ recommendation.color }} bg-opacity-10 p-4 rounded-lg border border-{{ recommendation.color }}">
                                        <h5 class="text-{{ recommendation.color }} mb-2"><i class="fa fa-{{ recommendation.icon }} mr-2"></i>{{ recommendation.title }}</h5>
                                        <p>{{ recommendation.description }}</p>
                                        {% if recommendation.action %}
                                        <div class="mt-3">
                                            <button class="btn btn-sm btn-{{ recommendation.color }}" onclick="{{ recommendation.action }}">{{ recommendation.action_text }}</button>
                                        </div>
                                        {% endif %}
                                    </div>
                                    {% endfor %}
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="row mt-4">
                    <div class="col">
                        <div class="card">
                            <div class="card-header">
                                <h5 class="card-title">节能效果预测</h5>
                            </div>
                            <div class="card-body">
                                <div class="chart-container small-chart">
                                    <canvas id="savingsPredictionChart"></canvas>
                                </div>
                                <div class="mt-4">
                                    <p><strong>预计月节省电量：</strong> {{ estimated_savings }} kWh</p>
                                    <p><strong>预计年节省电量：</strong> {{ estimated_savings_yearly }} kWh</p>
                                    <p><strong>预计节省费用：</strong> ¥{{ estimated_cost_savings }} /月</p>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // 时间范围设置函数
        function setTimeRange(range) {
            const today = new Date();
            let startDate, endDate;
            
            switch(range) {
                case 'today':
                    startDate = today.toISOString().split('T')[0];
                    endDate = today.toISOString().split('T')[0];
                    break;
                case 'week':
                    startDate = new Date(today.getTime() - 7 * 24 * 60 * 60 * 1000).toISOString().split('T')[0];
                    endDate = today.toISOString().split('T')[0];
                    break;
                case 'month':
                    startDate = new Date(today.getFullYear(), today.getMonth(), 1).toISOString().split('T')[0];
                    endDate = today.toISOString().split('T')[0];
                    break;
                case 'year':
                    startDate = new Date(today.getFullYear(), 0, 1).toISOString().split('T')[0];
                    endDate = today.toISOString().split('T')[0];
                    break;
            }
            
            document.getElementById('startDate').value = startDate;
            document.getElementById('endDate').value = endDate;
            updateAnalytics();
        }
        
        // 更新分析数据
        function updateAnalytics() {
            const startDate = document.getElementById('startDate').value;
            const endDate = document.getElementById('endDate').value;
            
            // 这里可以添加加载动画
            
            // 模拟数据更新 - 实际应用中应通过API获取新数据
            console.log(`更新分析数据: 从 ${startDate} 到 ${endDate}`);
            
            // 刷新页面或更新图表数据
            location.reload();
        }
        
        // 能耗趋势图
        const energyTrendCtx = document.getElementById('energyTrendChart').getContext('2d');
        const energyTrendChart = new Chart(energyTrendCtx, {
            type: 'line',
            data: {
                labels: {{ energy_dates | tojson }},
                datasets: [
                    {
                        label: '总能耗 (kWh)',
                        data: {{ energy_values | tojson }},
                        borderColor: '#007bff',
                        backgroundColor: 'rgba(0, 123, 255, 0.1)',
                        fill: true,
                        tension: 0.4
                    },
                    {
                        label: '预测能耗 (kWh)',
                        data: {{ predicted_energy | tojson }},
                        borderColor: '#ffc107',
                        borderDash: [5, 5],
                        backgroundColor: 'rgba(255, 193, 7, 0.05)',
                        fill: false,
                        tension: 0.4
                    }
                ]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    title: {
                        display: true,
                        text: '能耗变化趋势'
                    },
                    tooltip: {
                        mode: 'index',
                        intersect: false
                    }
                },
                scales: {
                    y: {
                        beginAtZero: true,
                        title: {
                            display: true,
                            text: '能耗 (kWh)'
                        }
                    },
                    x: {
                        title: {
                            display: true,
                            text: '日期'
                        }
                    }
                }
            }
        });
        
        // 设备能耗分布饼图
        const energyDistributionCtx = document.getElementById('energyDistributionChart').getContext('2d');
        const energyDistributionChart = new Chart(energyDistributionCtx, {
            type: 'doughnut',
            data: {
                labels: {{ device_names | tojson }},
                datasets: [{
                    data: {{ device_energy | tojson }},
                    backgroundColor: [
                        '#007bff',
                        '#28a745',
                        '#dc3545',
                        '#ffc107',
                        '#17a2b8',
                        '#6610f2',
                        '#fd7e14',
                        '#20c997'
                    ],
                    borderWidth: 1
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    title: {
                        display: true,
                        text: '设备能耗占比'
                    },
                    legend: {
                        position: 'right'
                    }
                }
            }
        });
        
        // 房间能耗对比柱状图
        const roomEnergyCtx = document.getElementById('roomEnergyChart').getContext('2d');
        const roomEnergyChart = new Chart(roomEnergyCtx, {
            type: 'bar',
            data: {
                labels: {{ room_names | tojson }},
                datasets: [{
                    label: '能耗 (kWh)',
                    data: {{ room_energy | tojson }},
                    backgroundColor: 'rgba(23, 162, 184, 0.7)',
                    borderColor: 'rgba(23, 162, 184, 1)',
                    borderWidth: 1
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    title: {
                        display: true,
                        text: '房间能耗对比'
                    }
                },
                scales: {
                    y: {
                        beginAtZero: true,
                        title: {
                            display: true,
                            text: '能耗 (kWh)'
                        }
                    }
                }
            }
        });
        
        // 用电高峰时段柱状图
        const peakHoursCtx = document.getElementById('peakHoursChart').getContext('2d');
        const peakHoursChart = new Chart(peakHoursCtx, {
            type: 'bar',
            data: {
                labels: ['0:00', '3:00', '6:00', '9:00', '12:00', '15:00', '18:00', '21:00'],
                datasets: [{
                    label: '平均能耗 (kWh)',
                    data: {{ hourly_energy | tojson }},
                    backgroundColor: 'rgba(255, 99, 132, 0.7)',
                    borderColor: 'rgba(255, 99, 132, 1)',
                    borderWidth: 1
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    title: {
                        display: true,
                        text: '用电高峰时段'
                    }
                },
                scales: {
                    y: {
                        beginAtZero: true,
                        title: {
                            display: true,
                            text: '能耗 (kWh)'
                        }
                    }
                }
            }
        });
        
        // 温度变化趋势图
        const temperatureCtx = document.getElementById('temperatureChart').getContext('2d');
        const temperatureChart = new Chart(temperatureCtx, {
            type: 'line',
            data: {
                labels: {{ temp_dates | tojson }},
                datasets: [{
                    label: '温度 (°C)',
                    data: {{ temp_values | tojson }},
                    borderColor: '#dc3545',
                    backgroundColor: 'rgba(220, 53, 69, 0.1)',
                    fill: true,
                    tension: 0.4
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    title: {
                        display: true,
                        text: '温度变化趋势'
                    }
                },
                scales: {
                    y: {
                        title: {
                            display: true,
                            text: '温度 (°C)'
                        }
                    },
                    x: {
                        title: {
                            display: true,
                            text: '时间'
                        }
                    }
                }
            }
        });
        
        // 湿度变化趋势图
        const humidityCtx = document.getElementById('humidityChart').getContext('2d');
        const humidityChart = new Chart(humidityCtx, {
            type: 'line',
            data: {
                labels: {{ humidity_dates | tojson }},
                datasets: [{
                    label: '湿度 (%)',
                    data: {{ humidity_values | tojson }},
                    borderColor: '#17a2b8',
                    backgroundColor: 'rgba(23, 162, 184, 0.1)',
                    fill: true,
                    tension: 0.4
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    title: {
                        display: true,
                        text: '湿度变化趋势'
                    }
                },
                scales: {
                    y: {
                        title: {
                            display: true,
                            text: '湿度 (%)'
                        }
                    },
                    x: {
                        title: {
                            display: true,
                            text: '时间'
                        }
                    }
                }
            }
        });
        
        // 节能效果预测图
        const savingsPredictionCtx = document.getElementById('savingsPredictionChart').getContext('2d');
        const savingsPredictionChart = new Chart(savingsPredictionCtx, {
            type: 'bar',
            data: {
                labels: ['当前', '实施建议后'],
                datasets: [{
                    label: '能耗 (kWh)',
                    data: [{{ current_energy }}, {{ optimized_energy }}],
                    backgroundColor: [
                        'rgba(255, 99, 132, 0.7)',
                        'rgba(75, 192, 192, 0.7)'
                    ],
                    borderColor: [
                        'rgba(255, 99, 132, 1)',
                        'rgba(75, 192, 192, 1)'
                    ],
                    borderWidth: 1
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    title: {
                        display: true,
                        text: '节能效果预测'
                    }
                },
                scales: {
                    y: {
                        beginAtZero: true,
                        title: {
                            display: true,
                            text: '能耗 (kWh)'
                        }
                    }
                }
            }
        });
        
        // 使用趋势图
        const usageTrendCtx = document.getElementById('usageTrendChart').getContext('2d');
        const usageTrendChart = new Chart(usageTrendCtx, {
            type: 'line',
            data: {
                labels: {{ usage_dates | tojson }},
                datasets: [
                    {% for device in device_usage_trends %}
                    {
                        label: '{{ device.name }}',
                        data: {{ device.values | tojson }},
                        borderColor: '{{ device.color }}',
                        tension: 0.4,
                        fill: false
                    },
                    {% endfor %}
                ]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    title: {
                        display: true,
                        text: '设备使用时长趋势'
                    },
                    tooltip: {
                        mode: 'index',
                        intersect: false
                    }
                },
                scales: {
                    y: {
                        beginAtZero: true,
                        title: {
                            display: true,
                            text: '使用时长 (小时)'
                        }
                    },
                    x: {
                        title: {
                            display: true,
                            text: '日期'
                        }
                    }
                }
            }
        });
        
        // 使用率雷达图
        const usageRateCtx = document.getElementById('usageRateChart').getContext('2d');
        const usageRateChart = new Chart(usageRateCtx, {
            type: 'radar',
            data: {
                labels: {{ device_names | tojson }},
                datasets: [{
                    label: '使用率 (%)',
                    data: {{ usage_rates | tojson }},
                    backgroundColor: 'rgba(54, 162, 235, 0.2)',
                    borderColor: 'rgba(54, 162, 235, 1)',
                    pointBackgroundColor: 'rgba(54, 162, 235, 1)',
                    pointBorderColor: '#fff',
                    pointHoverBackgroundColor: '#fff',
                    pointHoverBorderColor: 'rgba(54, 162, 235, 1)'
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    title: {
                        display: true,
                        text: '设备使用率'
                    }
                },
                scales: {
                    r: {
                        angleLines: {
                            display: true
                        },
                        suggestedMin: 0,
                        suggestedMax: 100
                    }
                }
            }
        });
        
        // 初始化页面时加载数据
        document.addEventListener('DOMContentLoaded', function() {
            // 这里可以添加初始化数据加载逻辑
            console.log('数据分析页面加载完成');
        });
    </script>
</body>
</html>